<?php


namespace App\Http\Controllers\Admin;


use App\Events\OrderFinished;
use App\Http\Controllers\Weapp\Order;
use App\Jobs\OrderNotice;
use App\Model\ReceiptCode;
use App\Service\Sms\SMSInterface;
use App\Tool\Json;
use App\Tool\NoticeType;
//use Illuminate\Http\Request;

class ReceiptCodeController extends AuthCheckController
{

    /**
     * 根据取货号查询订单
     * Create by PeterYang
     * 2020/06/22 20:22:16
     * Email:904801074@qq.com
     * @return false|string
     */
    function searchCode(){

        $code=request()->input('code');

        $data=ReceiptCode::where('code',$code)
            ->with('order.order_goods.goods')
            ->with('order.user')->first();

        if(!$data) return Json::code(2,'not found');

        return Json::code(1,'success',$data);
    }


    /**
     * 通过自提完成订单
     * Create by Peter
     * 2020/06/23 08:57:14
     * Email:904801074@qq.com
     */
    function orderFinishByCode(){


        try {

            \DB::beginTransaction();

            $code = request()->input('code');

            $data = ReceiptCode::where('code', $code)
                ->with('order.user')
                ->whereHas('order', function ($query) {

                    $query->where('status', 11);
                })
                ->first();

            if (!$data) return Json::code(2, '订单状态异常，请确认订单状态');

            $order_id = $data->order->id;

            \App\Model\Order::where('id', $order_id)->where('status', 11)
                ->update(['status' => 30]);


            $data->fill(['get_time'=>now()])->save();


            //订单完成事件
            event(new OrderFinished($data->order,$data->order->user));


            \DB::commit();

            return Json::code(1,'success');

        }catch (\Exception $exception){

            \DB::rollBack();

            return Json::code(2,$exception->getMessage());
        }


    }

    /**
     *
     * Create by PeterYang
     * 2020/07/02 20:03:43
     * Email:904801074@qq.com
     * @param SMSInterface $SMS
     */
    function getQuerySmsTemplate(SMSInterface $SMS){


//        $c=request()->validate([
//            'test'=>'required'
//        ]);

        $post=request()->input();

        $code=$post['code'];

        $data=$SMS->querySmsTemplate($code);


        return json_encode($data);

//        dd($data->toArray());

//        dd($c);

    }

}
